package com.willh.wz;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptedExpiryManager {
    private static final String PREF_NAME = "EncryptedExpiryPrefs";
    private static final String EXPIRY_DATE_KEY = "encryptedExpiryDate";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    private static final String SECRET_KEY = "YourSecretKey123"; // 请使用更强的密钥

    public static boolean checkExpiry(final Activity activity) {
        if (isAppExpired(activity)) {
            showExpiryInputDialog(activity);
        }
        if (isAppExpired(activity)) {
            return false;
        }
        return true;
    }

    private static boolean isAppExpired(Context context) {
        try {
            SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            String encryptedDateStr = prefs.getString(EXPIRY_DATE_KEY, null);
            if (encryptedDateStr == null) {
                return true; // 如果没有设置过期日期，认为已过期
            }

            String decryptedDateStr = decrypt(encryptedDateStr);
            Date expiryDate = DATE_FORMAT.parse(decryptedDateStr);
            Date currentDate = new Date();

            return currentDate.after(expiryDate);
        } catch (Exception e) {
            e.printStackTrace();
            return true; // 如果出现异常，假设应用已过期
        }
    }

    private static void showExpiryInputDialog(final Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("输入加密的过期时间");
        builder.setMessage("请输入加密后的过期时间字符串");

        final EditText input = new EditText(activity);
        builder.setView(input);

        builder.setPositiveButton("确定", null); // 我们稍后会设置这个按钮的监听器
        builder.setNegativeButton("取消", null); // 我们稍后会设置这个按钮的监听器

        final AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String encryptedExpiryDate = input.getText().toString();
                try {
                    String decryptedDate = decrypt(encryptedExpiryDate);
                    if (isValidDate(decryptedDate)) {
                        saveEncryptedExpiryDate(activity, encryptedExpiryDate);
                        Toast.makeText(activity, "新的过期日期已设置", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        // 重新检查过期状态
                        if (isAppExpired(activity)) {
                            Toast.makeText(activity, "应用已过期，请输入有效的密钥", Toast.LENGTH_LONG).show();
                            showExpiryInputDialog(activity);
                        }
                    } else {
                        showInvalidDateError(activity);
                    }
                } catch (Exception e) {
                    showInvalidInputError(activity);
                }
            }
        });

        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                // 应用已过期且用户取消了输入，关闭应用
                activity.finish();
            }
        });

        dialog.setCancelable(false); // 禁止通过后退键关闭对话框
    }

    private static boolean isValidDate(String dateStr) {
        try {
            Date date = DATE_FORMAT.parse(dateStr);
            Date currentDate = new Date();
            return date != null && date.after(currentDate);
        } catch (Exception e) {
            return false;
        }
    }

    private static void saveEncryptedExpiryDate(Context context, String encryptedExpiryDate) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(EXPIRY_DATE_KEY, encryptedExpiryDate).apply();
    }

    private static void showInvalidDateError(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("错误")
                .setMessage("解密后的日期格式无效或已过期。")
                .setPositiveButton("确定", null)
                .show();
    }

    private static void showInvalidInputError(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("错误")
                .setMessage("无效的加密字符串。")
                .setPositiveButton("确定", null)
                .show();
    }

    private static String decrypt(String input) throws Exception {
        SecretKeySpec keySpec = generateKey(SECRET_KEY);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedBytes = Base64.decode(input, Base64.DEFAULT);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    private static SecretKeySpec generateKey(String password) throws Exception {
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
        digest.update(bytes, 0, bytes.length);
        byte[] key = digest.digest();
        return new SecretKeySpec(key, "AES");
    }

    // 用于生成加密的过期时间字符串（通常在服务器端或安全环境中使用）
    public static String encrypt(String input) throws Exception {
        SecretKeySpec keySpec = generateKey(SECRET_KEY);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
    }
}